// index.js
// 获取应用实例
import { GlobalData } from '/store/state'
import { $event } from '/utils'
import { knowledgeApi } from '/api/konwledge'
import { getServer } from '/store/mutations'
import { userApi } from '/api/user'

Page({
  data: {
    navigationHeight: GlobalData.navigationHeight,
    access: GlobalData.access,
    currencyName: GlobalData.currencyName,
    noMore: false,
    navData: [{ id: 0, name: '全部', page: 1, isLastPage: false }] as any[],
    currentTab: 0,
    navScrollLeft: 0,
    list: [] as any[],
    currentTabList: [] as number[],
    canPublishKnowledge: false,
  },

  async onLoad() {
    const navData = await knowledgeApi.getKnowledgeClassify()
    navData.map((item) => (item.page = 1))
    this.setData({
      navData: [...this.data.navData, ...navData],
    })
    await this.onReset()
    $event.on('after:abilities', this, () => {
      this.power()
    })
    if (GlobalData.userAbilities.length == 0) {
      GlobalData.userAbilities = await userApi.abilitiesList()
      $event.emit('after:abilities')
    } else {
      this.power()
    }
  },
  onShow() {
    $event.on('after:boot', this, () => {
      this.getPostition()
    })
    this.getPostition()
  },
  async onReset() {
    wx.showLoading({
      title: '加载中',
    })
    const currentTab = this.data.currentTab
    const categoryId = this.data.navData[currentTab].id
    const page = 1
    const list = await knowledgeApi.getKnowledge({
      status: '1',
      category_id: categoryId > 0 ? categoryId : '',
      page: page,
      limit: 20,
      order: 'topped_at desc, updated_at desc',
    })
    const isLastPage =
      list.meta.last_page === list.meta.current_page || list.meta.last_page < list.meta.current_page
    const currentTabList = this.data.currentTabList
    currentTabList.push(this.data.currentTab)
    this.setData({
      [`list[${currentTab}]`]: list.data,
      [`navData[${currentTab}].isLastPage`]: isLastPage,
      currentTabList: currentTabList,
      [`navData[${currentTab}].page`]: 1,
      [`navData[${currentTab}].show`]: list.data.length === 0 ? true : false,
    })
    wx.hideLoading()
  },
  async onLoadmore() {
    if (this.data.navData[this.data.currentTab].isLastPage) {
      wx.showToast({
        title: '已没有更多了',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    const currentTab = this.data.currentTab
    const categoryId = this.data.navData[currentTab].id
    const page = this.data.navData[currentTab].page + 1
    const list = await knowledgeApi.getKnowledge({
      status: '1',
      category_id: categoryId > 0 ? categoryId : '',
      page: page,
      limit: 20,
      order: 'topped_at desc, updated_at desc',
    })
    const isLastPage =
      list.meta.last_page === list.meta.current_page || list.meta.last_page < list.meta.current_page
    this.setData({
      [`list[${currentTab}]`]: [...this.data.list[currentTab], ...list.data],
      [`navData[${currentTab}].page`]: list.meta.current_page,
      [`navData[${currentTab}].isLastPage`]: isLastPage,
    })
    wx.hideLoading()
  },
  onDownload() {
    $event.emit('download')
  },
  getPostition() {
    this.setData!({
      navigationHeight: GlobalData.navigationHeight,
      access: GlobalData.access,
      currencyName: GlobalData.currencyName,
    })
  },
  switchNav(event: WechatMiniprogram.CustomEvent) {
    const windowWidth = GlobalData.clientWidth
    const cur = event.currentTarget.dataset.current
    //每个tab选项宽度占1/5
    const singleNavWidth = windowWidth / 5
    //tab选项居中
    this.setData({
      navScrollLeft: (cur - 2) * singleNavWidth,
    })
    if (this.data.currentTab == cur) {
      return
    } else {
      this.setData({
        currentTab: cur,
      })
    }
  },
  switchTab(event: WechatMiniprogram.CustomEvent) {
    const windowWidth = GlobalData.clientWidth
    const cur = event.detail.current
    const singleNavWidth = windowWidth / 5
    this.setData({
      currentTab: cur,
      navScrollLeft: (cur - 2) * singleNavWidth,
    })
    this.switchList()
  },
  switchList() {
    //tab选中的改变和siwper滑动改变的方法写在这里
    const cur = this.data.currentTab
    //没有有缓存，切换Tab请求数据
    if (this.data.currentTabList.indexOf(cur) === -1) {
      this.onReset()
    }
  },
  toSerch() {
    const categoryId = this.data.navData[this.data.currentTab].id
    wx.navigateTo({ url: `/mall/search/search?categoryId=${categoryId}` })
  },

  async power() {
    const abilities: any = GlobalData.userAbilities
    const { data: user } = wx.getStorageSync(`${getServer()}/logged`)
    const canPublish =
      (await (await knowledgeApi.canPublishKnowledge({ user_id: user.id })).can_publish) ||
      (abilities && abilities.some((v: any) => v.name === 'knowledge:admin'))
    this.setData({
      canPublishKnowledge: canPublish,
    })
  },

  // 已购按钮
  goByiedKowndge() {
    wx.navigateTo({ url: '/index/knowledge/bought/bought' })
  },

  // 发布按钮
  goPublishKowndge() {
    if (this.data.canPublishKnowledge) {
      wx.navigateTo({ url: '/index/knowledge/publish/publish' })
    } else {
      wx.showToast({ title: '你还没有权限发布知识', icon: 'none' })
    }
  },
})
